package com.cngphone.AnFetion.Fetion.SIPC;

import java.util.ArrayList;

import org.w3c.dom.DOMException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;

import com.cngphone.AnFetion.FetionFriend;
import com.cngphone.AnFetion.FetionSIPC;
import com.cngphone.AnFetion.FetionUri;
import com.cngphone.AnFetion.Settings;
import com.cngphone.AnFetion.Fetion.TcpSendAndReceive;
import com.cngphone.AnFetion.tools.LogUtil;
import com.cngphone.AnFetion.tools.StrUtil;

public class IMInvite extends SIPCBase {
    private FetionUri fetionid;
    private FetionFriend info;
    private String nickname;
    private FetionSIPC invitesipc;
    private boolean isMobile = false;

    public IMInvite(SerialManager serialManager, TcpSendAndReceive connection, FetionUri fetionid,
            FetionFriend info, String nickname) {
        super(serialManager, connection);
        this.fetionid = fetionid;
        this.info = info;
        this.nickname = nickname;
    }

    @Override
    public boolean execute() {
        ArrayList<FetionSIPC.HeaderPair> headers = new ArrayList<FetionSIPC.HeaderPair>();
        headers.add(new FetionSIPC.HeaderPair("F", this.fetionid.getId()));
        headers.add(new FetionSIPC.HeaderPair("I", serialManager.getISerial() + " "));
        headers.add(new FetionSIPC.HeaderPair("Q", serialManager.getQSerial() + " S"));
        headers.add(new FetionSIPC.HeaderPair("N", "AddBuddy"));

        StringBuilder body = new StringBuilder();
        body.append("<args><contacts><buddies><buddy uri=\"").append(info.Uri).append("\"");
        body.append(" buddy-lists=\"\" desc=\"").append(StrUtil.toXml(nickname)).append(
                "\" expose-mobile-no=\"1\" expose-name=\"1\" addbuddy-phrase-id=\"0\"");
        body.append(" /></buddies></contacts></args>");
        headers.add(new FetionSIPC.HeaderPair("L", StrUtil.getLength(body)));

        invitesipc = new FetionSIPC(SIPC_COMMON_HEADER, headers, body.toString());
        if (this.SendAndReceiveResponse(invitesipc)) {
            try {
                String code = invitesipc.response.getResponseCmdLine().code;
                if (Settings.DEBUG) {
                	LogUtil.d("IMInvite", "[" + code + "] "
                            + invitesipc.response.getResponseCmdLine().description);
                }
                if (code.equals(SIPC_RESPONSE_CODE_OK)) {
                    Document dom = parseXmlDocument(invitesipc.response.body);
                    Element results = dom.getDocumentElement();

                    if (results != null && results.getNodeName().equals("results")) {
                        Node node = results.getFirstChild();
                        if (node != null && node.getNodeName().equals("contacts")) {
                            node = node.getFirstChild();
                            if (node != null && node.getNodeName().equals("buddies")) {
                                node = node.getFirstChild();
                                if (node != null && node.getNodeName().equals("buddy")) {
                                    NamedNodeMap attr = node.getAttributes();
                                    Node n = attr.getNamedItem("uri");
                                    if (Settings.DEBUG) {
                                    	LogUtil.d("IMInvite","find uri = " + n.getNodeValue());
                                    }
                                    if (n != null && !n.equals("")) info.Uri = n.getNodeValue();
                                }
                            }
                        }
                    }
                    return true;
                } else if (code.equals(SIPC_RESPONSE_CODE_NOSUBSCRIPTION)) {
                    isMobile = true;
                    headers = new ArrayList<FetionSIPC.HeaderPair>();
                    headers.add(new FetionSIPC.HeaderPair("F", this.fetionid.getId()));
                    headers.add(new FetionSIPC.HeaderPair("I", serialManager.getISerial() + " "));
                    headers.add(new FetionSIPC.HeaderPair("Q", serialManager.getQSerial() + " S"));
                    headers.add(new FetionSIPC.HeaderPair("N", "AddMobileBuddy"));

                    body = new StringBuilder();
                    body.append("<args><contacts><mobile-buddies><mobile-buddy uri=\"").append(info.Uri);
                    body.append("\"").append(" buddy-lists=\"\" desc=\"").append(StrUtil.toXml(nickname))
                            .append("\" invite=\"0\" addbuddy-phrase-id=\"0\"");
                    body.append(" /></mobile-buddies></contacts></args>");
                    headers.add(new FetionSIPC.HeaderPair("L", StrUtil.getLength(body)));

                    invitesipc = new FetionSIPC(SIPC_COMMON_HEADER, headers, body.toString());
                    if (this.SendAndReceiveResponse(invitesipc)) {
                        code = invitesipc.response.getResponseCmdLine().code;
                        if (code.equals(SIPC_RESPONSE_CODE_OK)) {
                            return true;
                        }
                    }
                }
            } catch (NumberFormatException e) {
                this.onSetText(e.getMessage());
                e.printStackTrace();
            } catch (DOMException e) {
                this.onSetText(e.getMessage());
                e.printStackTrace();
            } catch (Exception e) {
                this.onSetText(e.getMessage());
                e.printStackTrace();
            }
        }

        return false;
    }

    public boolean isMobile() {
        return isMobile;
    }
}
